package web.type;

import bean.Type;
import bean.Union;
import bean.User;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.TypeEntity;
import entity.UserEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "TypeList",urlPatterns = "/dao/typeList")
public class TypeList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String jsonString = FANREN.getJson(request);
        Union union = JSON.parseObject(jsonString,Union.class);
        System.out.println(union);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Query query;
        if(union.getSearch().equals("")){
            query = em.createQuery("select t from TypeEntity t");
        } else {
            query = em.createQuery("select t from TypeEntity t where t.name like '%" + union.getSearch() + "%'");
        }

        List<TypeEntity> list = query.getResultList();
        int totalPage = list.size();
        int pos = (union.getCurrentPage() - 1) * 8;

        List<Type> typesList = new ArrayList<>();
        for (int i=0,j=pos; i<8&&j<list.size(); i++,j++) {
            Type type = new Type(""+list.get(j).getTid(),""+list.get(j).getName());
            typesList.add(type);
        }
        String returnString = "{\"tableData\":" + JSON.toJSONString(typesList) +",\"totalPage\":" + totalPage + "}";
        response.getWriter().write(URLEncoder.encode(returnString,StandardCharsets.UTF_8));
    }
}
